import axios from "axios"
import { message } from 'antd'
import config from "../config"
import ssoWeb from '../libs/sso'
import localStorage from "./localStorage"

const service = axios.create({
    baseURL: config.baseUrl,
    timeout: 8000
})

// 请求拦截
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        // @ts-ignore
        config.headers['access-token'] = token
        // @ts-ignore
        config.headers['X-Requested-With'] = 'XMLHttpRequest'
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(response => {
    // 登录已过期或者未登录
    if (response.data.status === config.LOGIN_EXPIRE) {
        window.location.href = ssoWeb.getLoginUrl();
    }
    // 请求成功
    if (response.data.code === config.SUCCESS_CODE) {
        return response.data as any;
    }
    // 请求成功，状态不为成功时
    message.error(response.data.msg)
    return Promise.reject(new Error(response.data.msg))
}, error => {
    window.location.href = ssoWeb.getLoginUrl();
    message.warning('登录过期，正在重新登录...');
    return Promise.reject(error)
})

/**
 * 请求核心
 */
const request = (options: any) => {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data;
    }
    let customUrl = options.customUrl
    let isMock = config.mock;
    if (typeof options.mock != 'undefined') {
        isMock = options.mock;
    }
    if (config.env === 'production') {
        service.defaults.baseURL = config.baseUrl
    } else {
        service.defaults.baseURL = customUrl ? customUrl : (isMock ? config.mockUrl : config.baseUrl)
    }
    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item: string) => {
    // @ts-ignore
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request